<?php
namespace addons\ymypaylinx\library\paylinx;

class Base
{

    //商户号
    protected $mch_id;

    //门店ID
    protected $store_id;

    //密钥
    protected $key;

    //appid
    protected $appid;

    //回调
    protected $notify_url;
    // app下载地址
    protected $refer_url;



    public function __construct(array $items = [])
    {
        foreach ($items as $key => $value) {
           $this->set($value);
        }
    }
    /**
     * Set the item value.
     *
     * @param mixed $value
     */
    public function set($items)
    {
        foreach ($items as $key => $value){
            $this->$key = $value;
        }
    }


    //数组转XML
    public function arrayToXml($arr, $isRoot = true)
    {

        $xml = $isRoot ? "<xml>" : '';

        foreach ($arr as $key => $val) {

            if (is_array($val)) {

                $xml .= "<" . $key . ">" . $this->arrayToXml($val, false) . "</" . $key . ">";

            } else {

                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";

            }

        }

        $xml .= $isRoot ? "</xml>" : '';

        return $xml;

    }

    //将XML转为array
    public function xmlToArray($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }

    public function sign($data)
    {
        $str = '';
        ksort($data);
        foreach ($data as $key => $val) {
            if ((string)$val === '') {
                continue;
            }
            $str .= $key . '=' . $val . '&';
        }
        $str .= 'key=' . $this->key;
        $str = md5($str);
        $str = strtoupper($str);
        return $str;
    }

    public function httpsRequest($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_HTTPHEADER, ["Content-type: text/xml; charset=utf-8"]);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}